import os, sys
import subprocess
import time
from subprocess import Popen

class Experiment:

    def __init__(self, num_clients, time):
        self.process_list = []
        self.num_clients = num_clients
        self.time = time / 10
        self.file_size = "_small"
        self.request_rate_agg = 0
	self.time_agg = 0
	self.latency_agg = 0

    def run(self):
        for j in range(0,self.time):
	    self.time_agg = 0
            request_rate = 0
	    #self.latency_agg = 0
	    start_time = time.time()
            for i in range(0,self.num_clients):
                self.process_list.append(Popen(["python", "webserver.py", "10", "%s"%self.file_size], stdout=subprocess.PIPE))
            for i in range(0,self.num_clients):
                self.process_list[i].wait()
                strings = self.process_list[i].stdout.readlines()
                request_rate += float(strings[0])
		self.time_agg += float(strings[2])
		self.latency_agg += float(strings[1])
            self.process_list = []
	    end_time = time.time()
	    total_time = end_time - start_time
	    actual_rate = (request_rate * (self.time_agg / self.num_clients))/(total_time)
	    self.request_rate_agg += actual_rate
            print "%d(%d): %.02f(%.02f) : (%.02f)"%(self.num_clients, (1+j), (self.request_rate_agg / (j+1)), (actual_rate), self.latency_agg / (self.num_clients*(1+j)))
            time.sleep(2)

    def getResult(self):
        return self.request_rate_agg / self.time
        
if __name__ == '__main__' :

    num_procs = [2,8,16]
    load = [1,20,40,60]
    results = {}
    ret = 0
    
    for i in num_procs:
        ret = os.system('ssh server "cd badflow; ./makesys.sh %d attack && make -j" > /dev/null 2>> ./error.log'%i)
        if(ret == 0):
            print "Make with %d processors succeeded."%i
        line = []
        for j in load:
            ret = os.system('ssh server "cd attack; screen -d -m ./attack"')
            if(ret == 0):
                print "Execution of attack succeeded for load %d."%j
            else:
                exit("Execution failed with load %d."%j)
            time.sleep(5)
            exp = Experiment(j, 180)
            exp.run()
            line.append(exp.getResult())
            ret = os.system('ssh server "killall -9 attack"')
            if(ret == 0):
                print "Successfully killed attack for load %d."%j
            else:
                exit("Kill failed with load %d."%j)
        results[i] = line
    
    outfile = open("attack_loads.dat", 'w')
    outfile.write(str(results))




